package blog

import (
	"dustbe/database"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// 第一次询问，需要返回总博客数量、第一页的所有博客
func InitQuery(c *gin.Context) {
	maxBlogOnePage, _ := strconv.Atoi(c.Query("maxBlogOnePage"))
	blogNum, err := database.GetBlogNumber()
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	queryBlog, err := database.GetBlogByPage(1, maxBlogOnePage)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{
		"blogNum":   blogNum,
		"initBlogs": queryBlog,
	}})
}

func QueryRangeBlog(c *gin.Context) {
	max_seq, _ := strconv.Atoi(c.Query("max_seq"))
	min_seq, _ := strconv.Atoi(c.Query("min_seq"))

	queryBlog, err := database.GetRangeBlogBySeq(min_seq, max_seq)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": queryBlog})
}

func QueryBlogsByPageId(c *gin.Context) {
	pageId, _ := strconv.Atoi(c.Query("pageId"))

	queryBlog, err := database.GetBlogByPage(pageId, blogNumOnePage)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": queryBlog})
}

// 刚刚刷到话题路由下的初始化函数
func SearchByTags(c *gin.Context) {
	maxBlogOnePage, _ := strconv.Atoi(c.Query("maxBlogOnePage"))
	topicName := c.Query("topicName")

	blogNum, err := database.GetBlogNumByTopicName(topicName)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	queryBlog, err := database.GetAllBlogsByTopicName(topicName, 0, maxBlogOnePage-1)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{
		"blogNum": blogNum,
		"blogs":   queryBlog,
	}})
}

// 根据范围选取指定话题下的博客 begin 到 end 是全闭区间
func QueryRangeBlogByTopicName(c *gin.Context) {
	topicName := c.Query("topicName")
	begin, _ := strconv.Atoi(c.Query("begin"))
	end, _ := strconv.Atoi(c.Query("end"))

	queryBlog, err := database.GetAllBlogsByTopicName(topicName, begin, end)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4006, "msg": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"code": 200, "data": queryBlog})
}
